package com.funmi.lizip.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import com.funmi.lizip.common.base.DeleteRequest;
import com.funmi.lizip.common.base.R;
import com.funmi.lizip.common.exception.ApplicationException;
import com.funmi.lizip.entity.Camera;
import com.funmi.lizip.entity.Personnel;
import com.funmi.lizip.entity.RangersCollect;
import com.funmi.lizip.entity.dto.rangersCollect.RangersCollectAddRequest;
import com.funmi.lizip.entity.dto.rangersCollect.RangersCollectQueryRequest;
import com.funmi.lizip.entity.dto.rangersCollect.RangersCollectUpdateRequest;
import com.funmi.lizip.entity.enums.PathEnum;
import com.funmi.lizip.entity.vo.CameraVo;
import com.funmi.lizip.entity.vo.RangersCollectExcelVO;
import com.funmi.lizip.entity.vo.RangersCollectVo;
import com.funmi.lizip.mapper.RangersCollectMapper;
import com.funmi.lizip.service.PersonnelService;
import com.funmi.lizip.service.RangersCollectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author yeyg
 * @since 2022-11-03
 */
@Service
public class RangersCollectServiceImpl extends ServiceImpl<RangersCollectMapper, RangersCollect> implements RangersCollectService {

    @Autowired
    private RangersCollectMapper rangersCollectMapper;
    @Autowired
    private PersonnelService personnelService;

    @Override
    public Page<RangersCollectVo> queryList(RangersCollectQueryRequest request) {
        long current = 1;
        long size = 10;

        RangersCollect rangersCollectQuery = new RangersCollect();
        if (request != null) {
            BeanUtils.copyProperties(request, rangersCollectQuery);
            current = request.getPage();
            size = request.getPageSize();
        }
        QueryWrapper<RangersCollect> queryWrapper = new QueryWrapper<>(rangersCollectQuery);
        if (!ObjectUtils.isEmpty(rangersCollectQuery) && !ObjectUtils.isEmpty(request.getRangerId())) {
            queryWrapper.eq("rangerId", request.getRangerId());
        }

        Page<RangersCollect> rangersCollectPage = rangersCollectMapper.selectPage(new Page<>(current, size), queryWrapper);
        Page<RangersCollectVo> rangersCollectVoPage = new PageDTO(rangersCollectPage.getCurrent(), rangersCollectPage.getSize(), rangersCollectPage.getTotal());
        List<RangersCollectVo> rangersCollectVoList = rangersCollectPage.getRecords().stream().map(rangersCollect -> {
            RangersCollectVo rangersCollectVo = new RangersCollectVo();
            BeanUtils.copyProperties(rangersCollect, rangersCollectVo);

            if (rangersCollect.getPersonnelJson() != null) {
                rangersCollectVo.setPersonnelJson(rangersCollect.getPersonnelJson());
            }
            if (rangersCollect.getFileJson() != null) {
                rangersCollectVo.setFileJson(rangersCollect.getFileJson());
            }
            if (rangersCollect.getRangerid() != null && !Objects.equals(rangersCollect.getRangerid(), "")) {
                Personnel personnel = personnelService.getById(Integer.valueOf(rangersCollect.getRangerid()));
                if (!ObjectUtils.isEmpty(personnel)) {
                    rangersCollectVo.setName(personnel.getName());
                    rangersCollectVo.setContact_tel(personnel.getContactTel());
                }
            }
            return rangersCollectVo;
        }).collect(Collectors.toList());
        rangersCollectVoPage.setRecords(rangersCollectVoList);
        return rangersCollectVoPage;
    }

    @Override
    public boolean add(RangersCollectAddRequest request) throws IOException {
        if (request == null) {
            return false;
        }
        LocalDateTime now = LocalDateTime.now();
        String s="" + now.getYear() + "-" +  now.getMonthValue() + "-" +  now.getDayOfMonth();
        RangersCollect rangersCollect = JSONObject.parseObject(JSONObject.toJSONBytes(request), RangersCollect.class);
        if (!ObjectUtils.isEmpty(request.getFileJson())){
            String[] fileJson = request.getFileJson();

            JSONArray objects = new JSONArray();

            for (Object file : fileJson) {
                File dest = new File(PathEnum.PATH.getText() + "\\" + "RangersCollect"
                        + "\\" + rangersCollect.getEventType()  // 事件类型
                        + "\\" + s // 时间
                        + "\\" + file.toString());
                // 将暂存的图片移动到指定文件夹中
                // 文件夹名称
                Path directories = Files.createDirectories(dest.getParentFile().toPath());
                File startFile = new File(PathEnum.PATH.getText() + "\\" + file.toString());
                boolean b = startFile.renameTo(dest);
                if (!b) {
                    R.fail().message("图片保存失败");
                    throw new ApplicationException("图片保存失败");
                }
                // 添加到 JSONArray
                objects.add("\\"+rangersCollect.getEventType()  // 事件类型
                        + "\\" + s // 时间
                        + "\\" + file.toString());

            }

            rangersCollect.setFileJson(objects);
        }



        rangersCollect.setDelete(false);
        rangersCollect.setCreateAt(now);

        int insert = rangersCollectMapper.insert(rangersCollect);
        return insert == 1;
    }

    @Override
    public boolean delete(DeleteRequest request) {
        if (request == null || request.getId() <= 0) {
            return false;
        }
        RangersCollect rangersCollect = rangersCollectMapper.selectById(request.getId());
        if (rangersCollect == null) {
            return false;
        }
        int i = rangersCollectMapper.deleteById(rangersCollect.getId());
        return i == 1;
    }

    @Override
    public boolean updateBy(HashMap<String, Object> request) {
        if (request == null) {
            return false;
        }

        RangersCollect rangersCollect = JSONObject.parseObject(JSONObject.toJSONBytes(request), RangersCollect.class);
        if (rangersCollect.getId() < 0) {
            return false;
        }
        if (request.get("fileJson") != null && request.get("fileJson") != "") {
            rangersCollect.setFileJson(new JSONArray((List<Object>) request.get("fileJson")));
        }

        int i = rangersCollectMapper.updateById(rangersCollect);
        return i == 1;
    }

    @Override
    public void excelWrite(Integer type, HttpServletResponse response) throws IOException {
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String s = "资源信息";
        if (type == 2){
            s = "巡护事件";
        }
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode(s, "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        //3、指定需要那个class去写。然后写到第一个sheet，名字为模版，然后文件流会自动关闭

        EasyExcel.write(response.getOutputStream(), RangersCollectExcelVO.class).sheet(s).doWrite(data(type));


        // return R.success().message("导出完成");
    }

    private List<RangersCollectExcelVO> data(Integer type){
        //创建一个List集合
        List excelOrderList = new ArrayList<>();
        QueryWrapper<RangersCollect> wrapper = new QueryWrapper<>();
        wrapper.eq("event_type", type);
        wrapper.orderByDesc("create_at");
        List<RangersCollect> rangersCollects = rangersCollectMapper.selectList(wrapper);

        // 采集信息
        if (type == 1){
            for (RangersCollect rangersCollect : rangersCollects) {
                RangersCollectExcelVO data = new RangersCollectExcelVO();
                Personnel byId = personnelService.getById(rangersCollect.getRangerid());
                data.setTitle(rangersCollect.getTitle());
                data.setAddress(rangersCollect.getAddress());
                data.setCollectContent(rangersCollect.getCollectContent());
                data.setType(rangersCollect.getType());
                data.setName(byId.getName());
                data.setContact_tel(byId.getContactTel());
                data.setAlt(rangersCollect.getAlt());
                data.setCreateAt(rangersCollect.getCreateAt());
                excelOrderList.add(data);
            }
            return excelOrderList;
        }

        /*
         *xls版本的Excel最多一次可写0 ...65535行
         * xlsx 版本的Excel最多一次可写0...1048575行
         */
        //超出报异常：java.lang.IllegalArgumentException: Invalid row number (65536) outside allowable range (0..65535)
        for (RangersCollect rangersCollect : rangersCollects) {
            RangersCollectExcelVO data = new RangersCollectExcelVO();
            Personnel byId = personnelService.getById(rangersCollect.getRangerid());
            data.setTitle(rangersCollect.getTitle());
            data.setAddress(rangersCollect.getAddress());
            data.setCollectContent(rangersCollect.getCollectContent());
            data.setType(rangersCollect.getType());
            data.setName(byId.getName());
            data.setContact_tel(byId.getContactTel());
            data.setAlt(rangersCollect.getAlt());
            data.setPersonnelJson(rangersCollect.getPersonnelJson());
            data.setCreateAt(rangersCollect.getCreateAt());
            excelOrderList.add(data);
        }
        //返回list集合
        return excelOrderList;
    }
}
